package cn.view;

import cn.comon.CSVUtil;
import cn.comon.VerticalTextCellRenderer;
import cn.dao.ClientDao;
import cn.entity.Client;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ClientManageView extends JInternalFrame {
    JTable detail;
    DefaultTableModel model;
    JPanel Jbutton;

    public ClientManageView() {
        super("客户管理页面", false, true, false, true);
        initializeComponents();
        this.setSize(800, 500);
        this.setVisible(true);
    }

    private void initializeComponents() {
        // 设置布局管理器
        getContentPane().setLayout(new BorderLayout());
        // 初始化数据和按钮
        getDetailData();
        setButton();
    }

    private void getDetailData() {
        ClientDao dao = new ClientDao();
        List<Object[]> ls = dao.selectAll();
        String[] title = { "客户编号", "客户名称", "客户简称", "地址", "公司电话", "邮件", "联系人", "联系人电话", "备注" };
        model = new DefaultTableModel(ls.toArray(new Object[][]{}), title);
        detail = new JTable(model);
        detail.setDefaultEditor(Object.class, null);
        detail.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        // 设置表格列宽
        setColumnWidths(detail, new int[]{50,85,55,90,90,90,80,90,140});
        // 设置表格行高
        detail.setRowHeight(15);
        // 设置自定义渲染器
        for(int i = 0; i < detail.getColumnCount(); i++)
        {
            detail.getColumnModel().getColumn(i).setCellRenderer(new VerticalTextCellRenderer());
        }


        JScrollPane scrollPane = new JScrollPane(detail, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
    }

    private void setColumnWidths(JTable table, int[] widths) {
        for (int i = 0; i < widths.length; i++) {
            table.getColumnModel().getColumn(i).setPreferredWidth(widths[i]);
        }
    }


    public void refreshClientData(){
        ClientDao dao = new ClientDao();
        List<Object[]> ls = dao.selectAll();
        model.setRowCount(0);
        for (Object[] row : ls) {
            model.addRow(row);
        }
    }

    private JPanel createClientFormPanel(JTextField[] fields) {
        for(int i = 0; i < fields.length; i++)
        {
            fields[i] = new JTextField(10);
        }


        JPanel panel = new JPanel(new GridLayout(9, 2));
        panel.add(new JLabel("客户编号:"));
        panel.add(fields[0]);
        panel.add(new JLabel("客户名称:"));
        panel.add(fields[1]);
        panel.add(new JLabel("客户简称:"));
        panel.add(fields[2]);
        panel.add(new JLabel("地址:"));
        panel.add(fields[3]);
        panel.add(new JLabel("公司电话:"));
        panel.add(fields[4]);
        panel.add(new JLabel("邮件:"));
        panel.add(fields[5]);
        panel.add(new JLabel("联系人:"));
        panel.add(fields[6]);
        panel.add(new JLabel("联系人电话:"));
        panel.add(fields[7]);
        panel.add(new JLabel("备注:"));
        panel.add(fields[8]);

        return panel;
    }

    private Client getClientFromFields(JTextField[] fields) {
        Client client = new Client();
        client.setCid(fields[0].getText());
        client.setCName(fields[1].getText());
        client.setShortName(fields[2].getText());
        client.setAddress(fields[3].getText());
        client.setCompanyPhone(fields[4].getText());
        client.setEmail(fields[5].getText());
        client.setContact(fields[6].getText());
        client.setContactPhone(fields[7].getText());
        client.setNotes(fields[8].getText());
        return client;
    }

    private List<Client> convertToClientList(List<Object[]> data) {
        List<Client> clients = new ArrayList<>();
        for (Object[] row : data) {
            Client client = new Client();
            client.setCid((String) row[0]);
            client.setCName((String) row[1]);
            client.setShortName((String) row[2]);
            client.setAddress((String) row[3]);
            client.setCompanyPhone((String) row[4]);
            client.setEmail((String) row[5]);
            client.setContact((String) row[6]);
            client.setContactPhone((String) row[7]);
            client.setNotes((String) row[8]);
            clients.add(client);
        }
        return clients;
    }

    private void showAddClientDialog() {
        JTextField[] fields = new JTextField[9];
        JPanel panel = createClientFormPanel(fields);

        int result = JOptionPane.showConfirmDialog(null, panel, "添加客户", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            Client client = getClientFromFields(fields);

            ClientDao dao = new ClientDao();
            List<Client> clientList = new ArrayList<>();
            clientList.add(client);
            dao.addClient(clientList);

            // 更新表格视图
            model.addRow(new Object[]{
                    client.getCid(),
                    client.getCName(),
                    client.getShortName(),
                    client.getAddress(),
                    client.getCompanyPhone(),
                    client.getEmail(),
                    client.getContact(),
                    client.getContactPhone(),
                    client.getNotes()
            });
            refreshClientData();
        }
    }

    private void showEditClientDialog(int selectedRow) {
        JTextField[] fields = new JTextField[9];
        JPanel panel = createClientFormPanel(fields);

        // 填充现有数据
        for(int i = 0; i < fields.length; i++)
        {
            fields[i].setText((String) model.getValueAt(selectedRow, i));
        }


        int result = JOptionPane.showConfirmDialog(null, panel, "修改客户", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            String originalCid = (String) model.getValueAt(selectedRow, 0);
            Client client = getClientFromFields(fields);

            ClientDao dao = new ClientDao();
            dao.updateClient(client, originalCid);

            // 更新表格视图
            model.setValueAt(client.getCid(), selectedRow, 0);
            model.setValueAt(client.getCName(), selectedRow, 1);
            model.setValueAt(client.getShortName(), selectedRow, 2);
            model.setValueAt(client.getAddress(), selectedRow, 3);
            model.setValueAt(client.getCompanyPhone(), selectedRow, 4);
            model.setValueAt(client.getEmail(), selectedRow, 5);
            model.setValueAt(client.getContact(), selectedRow, 6);
            model.setValueAt(client.getContactPhone(), selectedRow, 7);
            model.setValueAt(client.getNotes(), selectedRow, 8);
        }
    }

    private void showQueryClientDialog() {
        JTextField[] fields = new JTextField[9];
        JPanel panel = createClientFormPanel(fields);

        int result = JOptionPane.showConfirmDialog(null, panel, "查询客户", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            Client criteria = getClientFromFields(fields);

            ClientDao dao = new ClientDao();
            List<Client> clients = dao.queryClients(criteria);

            if (clients.isEmpty()) {
                JOptionPane.showMessageDialog(null, "没有符合客户信息");
            } else {
                // 清空现有表格数据
                model.setRowCount(0);
                // 添加查询结果到表格
                for (Client client : clients) {
                    model.addRow(new Object[]{
                            client.getCid(),
                            client.getCName(),
                            client.getShortName(),
                            client.getAddress(),
                            client.getCompanyPhone(),
                            client.getEmail(),
                            client.getContact(),
                            client.getContactPhone(),
                            client.getNotes()
                    });
                }
            }
        }
    }

    private void showExportClientDialog() {
        String[] options = {"导出所有客户数据", "导出筛选后的客户数据", "导出除筛选外的客户数据"};
        int choice = JOptionPane.showOptionDialog(
                null,
                "请选择导出选项",
                "导出客户数据",
                JOptionPane.DEFAULT_OPTION,
                JOptionPane.INFORMATION_MESSAGE,
                null,
                options,
                options[0]
        );

        // 如果用户选择关闭对话框或点击取消按钮，直接返回
        if (choice == JOptionPane.CLOSED_OPTION) {
            return;
        }

        List<Client> clientsToExport = new ArrayList<>();

        if (choice == 0) { // 导出所有客户数据
            ClientDao dao = new ClientDao();
            List<Object[]> allClientsData = dao.selectAll();
            clientsToExport = convertToClientList(allClientsData);
        } else {
            JTextField[] fields = new JTextField[9];
            JPanel panel = createClientFormPanel(fields);

            int result = JOptionPane.showConfirmDialog(null, panel, "筛选客户", JOptionPane.OK_CANCEL_OPTION);
            // 如果用户选择关闭对话框或点击取消按钮，直接返回
            if (result == JOptionPane.CLOSED_OPTION || result == JOptionPane.CANCEL_OPTION) {
                return;
            }

            Client criteria = getClientFromFields(fields);
            ClientDao dao = new ClientDao();
            List<Client> filteredClients = dao.queryClients(criteria);

            if (choice == 1) { // 导出筛选后的客户数据
                clientsToExport = filteredClients;
            } else if (choice == 2) { // 导出除筛选外的客户数据
                List<Object[]> allClientsData = dao.selectAll();
                clientsToExport = convertToClientList(allClientsData);
            }
        }

        if (!clientsToExport.isEmpty()) {
            exportClientsToCSV(clientsToExport);
        } else {
            JOptionPane.showMessageDialog(null, "没有符合条件的客户数据可导出");
        }
    }

    private void exportClientsToCSV(List<Client> clients) {
        String[] headers = {"客户编号", "客户名称", "客户简称", "地址", "公司电话", "邮件", "联系人", "联系人电话", "备注"};
        List<Object[]> data = new ArrayList<>();

        for (Client client : clients) {
            data.add(new Object[]{
                    client.getCid(),
                    client.getCName(),
                    client.getShortName(),
                    client.getAddress(),
                    client.getCompanyPhone(),
                    client.getEmail(),
                    client.getContact(),
                    client.getContactPhone(),
                    client.getNotes()
            });
        }

        File csvFile = CSVUtil.createCSVFile(headers, data, "output/path", "客户数据");
        if (csvFile != null) {
            JOptionPane.showMessageDialog(null, "客户数据已成功导出到: " + csvFile.getAbsolutePath());
        } else {
            JOptionPane.showMessageDialog(null, "导出客户数据失败");
        }
    }

    private void setButton() {
        Jbutton = new JPanel();
        Jbutton.setLayout(new FlowLayout());

        JButton addButton = new JButton("添加客户");
        addButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showAddClientDialog();
            }
        });

        JButton editButton = new JButton("修改客户");
        editButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int selectedRow = detail.getSelectedRow();
                if (selectedRow != -1) {
                    showEditClientDialog(selectedRow);
                } else {
                    JOptionPane.showMessageDialog(null, "请选择要修改的客户");
                }
            }
        });

        JButton delButton = new JButton("删除客户");
        delButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                int selectedRow = detail.getSelectedRow();
                if (selectedRow != -1) {
                    String cid = (String) model.getValueAt(selectedRow, 0);
                    ClientDao dao = new ClientDao();
                    dao.deleteClient(cid);
                    model.removeRow(selectedRow);
                } else {
                    JOptionPane.showMessageDialog(null, "请选择要删除的客户");
                }
            }
        });

        JButton queryButton = new JButton("查询客户");
        queryButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showQueryClientDialog();
            }
        });

        JButton exportButton = new JButton("导出客户数据");
        exportButton.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                showExportClientDialog();
            }
        });

        Jbutton.add(addButton);
        Jbutton.add(editButton);
        Jbutton.add(delButton);
        Jbutton.add(queryButton);
        Jbutton.add(exportButton);

        getContentPane().add(Jbutton, BorderLayout.SOUTH);
    }
}
